﻿using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.Infrastructure.Filters
{

    public class GlobalExceptionFilter
        : ActionFilterAttribute, IExceptionFilter
    {

        public GlobalExceptionFilter()
            : base()
        {
        }

        public void OnException(ExceptionContext context)
        {
            var ctx = context.HttpContext;
            if (ctx.Request.Path.StartsWithSegments("/api"))
            {
                ctx.Response.OnStarting(async () =>
                {
                    ctx.Response.Clear();
                    ctx.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    await ctx.Response.WriteAsync(JsonConvert.SerializeObject(new
                    {
                        Message = context.Exception.Message,
                        Stacktrace = context.Exception.StackTrace
                    }));
                });
            }
        }

    }

}